package icu.xuyijie.mysecondspringboot.controller;

import icu.xuyijie.mysecondspringboot.entity.Teacher;
import icu.xuyijie.mysecondspringboot.mapper.TeacherMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.List;

/**
 * @author 徐一杰
 * @date 2024/11/19 8:40
 * @description
 */
@Controller
@RequestMapping("/teacher")
@Slf4j
public class TeacherController {

    @Autowired
    private TeacherMapper teacherMapper;

    @GetMapping("/findAll")
    public String findAll(Model model, Teacher teacher) {
        // 查询数据库教师信息，展示到页面
        List<Teacher> teacherList = teacherMapper.findAll(teacher);
        model.addAttribute("dataList", teacherList);

        return "teacherList";
    }

    @GetMapping("/goAddTeacher")
    public String goAddTeacher(Model model, Integer id) {
        // 新增按钮情况
        if (id == null) {
            model.addAttribute("tc", new Teacher());
        } else {
            // 根据 id 查询数据信息
            Teacher teacher = teacherMapper.findTeacherById(id);
            model.addAttribute("tc", teacher);
        }
        return "addTeacher";
    }

    @PostMapping("/saveTeacher")
    public String saveTeacher(Integer id, String name, String sex) {
        // 新增按钮情况
        if (id == null) {
            teacherMapper.inertTeacher(name, sex, new Date());
        } else  {
            // 更新表单数据到数据库
            teacherMapper.updateTeacherById(id, name, sex);
        }

        // 重新加载列表页
        return "redirect:/teacher/findAll";
    }

    @GetMapping("/deleteTeacher")
    public String deleteTeacher(Integer id) {
        teacherMapper.deleteById(id);
        // 重新加载列表页
        return "redirect:/teacher/findAll";
    }

}
